// axios二次封装
import axios from "axios";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";

const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // env文件定义的baseUrl
  timeout: 6000
});

// 请求拦截
request.interceptors.request.use(config => {
  const userStore = useUserStore();
  if (userStore.token) {
    config.headers.authorization = userStore.token;
  }
  return config;
});

// 响应拦截
request.interceptors.response.use(
  resp => {
    return resp.data;
  },
  err => {
    let message = "";
    let status = err.response.status;
    switch (status) {
      case 401:
        message = "Unauthorized";
        break;
      case 403:
        message = "Forbidden";
        break;
      case 404:
        message = "Not Found";
        break;
      case 500:
        message = "Internal Server Error";
        break;
      default:
        message = "network error";
        break;
    }
    ElMessage({
      type: "error",
      message
    });
  }
);

export default request;
